package com.playlist.listainteligente.condicao;

import com.playlist.PlaylistC;
import com.playlist.PlaylistI;
import com.serial.PortaCDs;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author rudieri
 */
public class JListaInteligenteEditor extends javax.swing.JDialog implements ActionListener, WindowListener {

    private PlaylistC playlist;

    /**
     * Creates new form JListaInteligenteEditor
     *
     * @param parent
     * @param modal
     */
    public JListaInteligenteEditor(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

    }

    public void atualizarCondicoes(PlaylistC playlist) {
        try {
            jPanel_Condicoes.removeAll();
            for (int i = 0; i < playlist.getCondicoes().size(); i++) {
                Condicao condicao = playlist.getCondicoes().get(i);
                JCondicao jCondicao = new JCondicao();
                jCondicao.setCondicao(condicao);
                jPanel_Condicoes.add(jCondicao);
            }
        } catch (Exception ex) {
            Logger.getLogger(JListaInteligenteEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setPlaylist(PlaylistC playlist) {
        this.playlist = playlist;
        if (playlist == null) {
            adicionarCondicao();
            jTextField_Nome.setText("");
        } else {
            jTextField_Nome.setText(playlist.getNome());
            atualizarCondicoes(playlist);
        }
    }

    public PlaylistC getPlaylist() {
        return playlist;
    }

    private void salvar() {
        try {
            if (jTextField_Nome.getText().isEmpty()) {
                throw new IllegalStateException("Informa um nome para sua nova lista.");
            }
            PlaylistI plI = PortaCDs.getPlaylist(jTextField_Nome.getText(), true, PlaylistC.class);
            if (!(plI instanceof PlaylistC)) {
                throw new IllegalStateException("Já existe uma lista com esse nome.\nEscolha outro.");
            }
            playlist = (PlaylistC) plI;
            playlist.getCondicoes().clear();
            
            for (int i = 0; i < jPanel_Condicoes.getComponentCount(); i++) {
                Component component = jPanel_Condicoes.getComponent(i);
                if (component.getClass() == JCondicao.class) {
                    Condicao condicao = ((JCondicao) component).getCondicao();
                    playlist.addCondicao(condicao);
                }
            }
            dispose();
        } catch (Exception ex) {
            if (ex instanceof IllegalStateException) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }else{
                ex.printStackTrace(System.err);
            }
        }
    }

    private void adicionarCondicao() {
        JCondicao jCondicao = new JCondicao();
        jPanel_Condicoes.add(jCondicao, jPanel_Condicoes.getComponentCount() - 1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField_Nome = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel_Condicoes = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(this);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jLabel1.setText("Nome:");
        jLabel1.setPreferredSize(new java.awt.Dimension(70, 15));
        jPanel2.add(jLabel1, java.awt.BorderLayout.WEST);
        jPanel2.add(jTextField_Nome, java.awt.BorderLayout.CENTER);

        jButton3.setText("Adicionar uma Condição");
        jButton3.addActionListener(this);
        jPanel2.add(jButton3, java.awt.BorderLayout.LINE_END);

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_START);

        jButton1.setText("Salvar");
        jButton1.addActionListener(this);
        jPanel1.add(jButton1);

        jButton2.setText("Cancelar");
        jButton2.addActionListener(this);
        jPanel1.add(jButton2);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel_Condicoes.setLayout(new javax.swing.BoxLayout(jPanel_Condicoes, javax.swing.BoxLayout.Y_AXIS));
        jScrollPane1.setViewportView(jPanel_Condicoes);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        setSize(new java.awt.Dimension(757, 382));
        setLocationRelativeTo(null);
    }

    // Code for dispatching events from components to event handlers.

    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == jButton1) {
            JListaInteligenteEditor.this.jButton1ActionPerformed(evt);
        }
        else if (evt.getSource() == jButton2) {
            JListaInteligenteEditor.this.jButton2ActionPerformed(evt);
        }
        else if (evt.getSource() == jButton3) {
            JListaInteligenteEditor.this.jButton3ActionPerformed(evt);
        }
    }

    public void windowActivated(java.awt.event.WindowEvent evt) {
    }

    public void windowClosed(java.awt.event.WindowEvent evt) {
    }

    public void windowClosing(java.awt.event.WindowEvent evt) {
        if (evt.getSource() == JListaInteligenteEditor.this) {
            JListaInteligenteEditor.this.formWindowClosing(evt);
        }
    }

    public void windowDeactivated(java.awt.event.WindowEvent evt) {
    }

    public void windowDeiconified(java.awt.event.WindowEvent evt) {
    }

    public void windowIconified(java.awt.event.WindowEvent evt) {
    }

    public void windowOpened(java.awt.event.WindowEvent evt) {
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        playlist = null;
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        salvar();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        adicionarCondicao();
//        Rectangle visibleRect = jScrollPane1.getVisibleRect();
//        System.out.println(visibleRect);
//        visibleRect.y = jPanel_Condicoes.getHeight();//-visibleRect.height;
//        System.out.println(visibleRect);
//        jScrollPane1.scrollRectToVisible(visibleRect);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        playlist = null;
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel_Condicoes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField_Nome;
    // End of variables declaration//GEN-END:variables
}
